import {
	Toast
} from '@/utils/common.js'
import {
	User
} from "@/utils/user.js"

export const VITE_API_URL = "http://192.168.2.126:9999";
export const IMG_SERVER = "http://192.168.2.126:9999";

export const SUCCESS_CODE = 200;
export const TOKEN_ERROR = 999;

export const toLogin = () => {
	console.log("token无效，返回登陆页面...");
	uni.navigateTo({
		url: "/pages/login/index"
	})
}

export const Request = {
	get(url, params) {
		return Request.doRequest("GET", url, params);
	},
	post(url, data) {
		return Request.doRequest("POST", url, data);
	},
	del(url,params){
		return Request.doRequest("DELETE",url,params);
	},
	doRequest(method, url, data) {

		let token = User.getToken();
		let header = {
			"UserRole": "Member",
			"token": token == null ? "" : token,
			"Content-Type": "application/json"
		};

		return new Promise((resolve, reject) => {
			uni.request({
				header: header,
				method: method,
				url: VITE_API_URL + url,
				dataType: "json",
				data: data,
				success(res) {
					console.log("请求成功，返回信息：", res);
					if (res.statusCode && res.statusCode == 401) {
						//token有问题
						toLogin();
					}
					res = res.data;
					if (res.code != SUCCESS_CODE) {
						Toast.error(res.message);
						reject(res.message);
					} else {
						//okFun(res.result);
						resolve(res.result);
					}
				},
				fail(res) {
					console.log("请求失败，返回信息：", res);
					Toast.error("请求失败");
					reject(res);
				},
			});
		});
	},
}
